import { ref, reactive, computed } from 'vue'
import { useRoleStore } from '@/stores/pages/role.js'
import { ElMessage } from 'element-plus'

export function useRoleForm(type = 'add') {
    const roleStore = useRoleStore()

    const form = reactive({
        id: null,
        roleName: '',
        description: '',
        permissions: [],
        status: true
    })

    const formRef = ref(null)
    const permissionTreeRef = ref(null)
    const dialogVisible = ref(false)

    const permissionTreeData = computed(() => roleStore.getPermissionTreeData)

    // 角色变化处理
    const handleRoleChange = (roleName) => {
        if (!roleName) return
        
        const recommendedPermissions = roleStore.getRolePermissions(roleName)
        form.permissions = [...recommendedPermissions]

        if (permissionTreeRef.value && typeof permissionTreeRef.value.setCheckedKeys === 'function') {
            permissionTreeRef.value.setCheckedKeys(form.permissions)
        }
    }

    // 权限选择处理
    const handlePermissionCheck = (data, info) => {
        if (!info || !Array.isArray(info.checkedKeys)) return
        
        form.permissions = info.checkedKeys.filter(key =>
            typeof key === 'string' && key.includes(':')
        )
    }

    // 获取选中的权限
    const getCheckedPermissions = () => {
        return Array.isArray(form.permissions) ? form.permissions : []
    }

    // 重置表单
    const resetForm = () => {
        Object.assign(form, {
            id: null,
            roleName: '',
            description: '',
            permissions: [],
            status: true
        })
        
        if (permissionTreeRef.value && typeof permissionTreeRef.value.setCheckedKeys === 'function') {
            permissionTreeRef.value.setCheckedKeys([])
        }
    }

    // 打开对话框
    const openDialog = (rowData = null) => {
        if (rowData && typeof rowData === 'object') {
            // 编辑模式
            Object.assign(form, {
                id: rowData.id,
                roleName: rowData.roleName || '',
                description: rowData.description || '',
                permissions: Array.isArray(rowData.permissions) ? [...rowData.permissions] : [],
                status: rowData.status === 1
            })
        } else {
            // 添加模式
            resetForm()
        }
        dialogVisible.value = true
    }

    return {
        form,
        formRef,
        permissionTreeRef,
        dialogVisible,
        permissionTreeData,
        handleRoleChange,
        handlePermissionCheck,
        getCheckedPermissions,
        resetForm,
        openDialog
    }
}